import React, { useState, useRef, useEffect } from 'react';
import styles from './index.less';
import { Icon } from 'tinper-bee';

export default props => {
    const { checked, closable, onClose, value, onChange, disabled } = props;

    const [visible, setVisible] = useState(true);
    const [tagChecked, setTagChecked] = useState(checked);
    const closeRef = useRef();

    const deleteTag = async e => {
        let res = await onClose(value, props.children);

        if (res !== false) {
            setVisible(false);
        }
    };

    const changeChecked = e => {
        if (disabled) {
            return;
        }
        if (!e.target.className.includes('uf-close')) {
            onChange(!tagChecked);
            setTagChecked(!tagChecked);
        }
    };

    useEffect(() => {
        setTagChecked(checked);
    }, [checked]);

    return (
        <span
            className={`${styles['tag-box']} ${tagChecked ? styles['checked'] : ''} custom-tag`}
            style={{
                display: visible ? 'block' : 'none',
                paddingRight: closable ? 0 : '8px'
            }}
            onClick={changeChecked}
        >
            <span>{props.children}</span>
            {closable ? (
                <span className={styles['tag-icon']}>
                    <Icon type="uf-close" onClick={deleteTag} ref={closeRef} />
                </span>
            ) : null}
        </span>
    );
};
